<template>
  <view class="head" style="background-color: #ffcc00;
  height: 180rpx;
  display: flex;">
    <img style="height: 50rpx;
    width: 50rpx;
    padding: 10rpx;
    margin-top: 15%;" src="../../../static/tabbar/返回.png" alt="" @click="handleReturn"></img>
    <view style="
    height: fit-content;
     margin-top: 15%;
     margin-left: 30%;
     font-size: 32rpx;">护工端-首页</view>
  </view>
 
  <view class="page">
    <wd-search v-model="value" placeholder-left hide-cancel maxlength="10" class="search-wrapper" @search="search" />
    <view class="swiper-container">
      <wd-swiper :list="swiperList" autoplay v-model:current="current" :indicator="{ type: 'fraction' }"
        indicatorPosition="bottom-right">
        <template #item="{ item }">
          <image :src="item" mode="aspectFill" style="width: 100%; height: 100%;"
            @error="() => handleImageError(item)" />
        </template>
      </wd-swiper>
      <text class="title">公司福利发放</text>
      <wd-button custom-class="custom-shadow" @click="handleBannerDetail(current)">立即了解</wd-button>
    </view>
    
    <view class="notice" @click="handleNoticeClick">
      <image src="../../../static/icons/notice.svg" alt="" />
      <text class="label">通知</text>
      <view class="split"></view>
      <text class="value">{{ noticeContent }}</text>
      <wd-icon name="arrow-right" size="22rpx" style="margin-left: 32rpx; color: #c7c7cc"></wd-icon>
    </view>


    <view class="content">
      <view v-for="(item, index) in messageList" :key="index" class="list-item"
        @click="handleContentClick(item.content)">
        <image :src="item.cover" />
        <view class="list-item-info">
          <text>{{ item.title }}</text>
          <view class="items">
            <text>{{ item.date }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
  <view class="nurse-tabbar">
    <view v-for="(item, index) in tabList" :key="index" class="tab-item" :class="{ active: currentIndex === index }"
      @click="handleTabClick(index)">
      <image :src="currentIndex === index ? item.selectedIconPath : item.iconPath" class="tab-icon" />
      <text class="tab-text">{{ item.text }}</text>
    </view>
  </view>
  
</template>

<script setup>
import usePage from "@/hooks/usePage.js"
import useLoading from "@/hooks/useLoading.js"
import { ref, onMounted } from 'vue'
import { getNoticeList } from '@/api/content/banner'
import { getActivityArticle } from '@/api/content/article'
import { getNurseBannerList } from '@/api/content/banner'
import { getUserOrderList, updateUserOrderStatus } from '@/api/wxlogin/wxlogin'

const handleReturn = () => {
  uni.navigateTo({ url: '/pages/entrance/index' })
}
const { loading, setLoading } = useLoading()

const { systemBarHeight, menuBotton } = usePage()

const swiperList = ref([])
const current = ref(0)
const richText = ref([])

const messageList = ref([
  // { 
  //   title: '养老护理员学习课程上线， 提供多套练习题，快来训练吧！',
  //   cover: 'https://cloud-minapp-47896.cloud.ifanrusercontent.com/1tNSlrQXZAIxaYqO.jpg'
  // },
  // { 
  //   title: '目前开放养老护理员题库刷题功能, 其他功能将陆续推出！',
  //   cover: 'https://cloud-minapp-47896.cloud.ifanrusercontent.com/1tNSlryT3gzZWJOz.jpg'
  // },
  // { 
  //   title: '护工小程序1.0版本上线啦！',
  //   cover: 'https://cloud-minapp-47896.cloud.ifanrusercontent.com/1tNSlrK5hiVLU9BQ.jpg'
  // },
])

const fetchNurseBannerData = async () => {
  try {
    const res = await getNurseBannerList()
    if (res.data && Array.isArray(res.data)) {
      swiperList.value = res.data.map(item => item.url)
      richText.value = res.data.map(item => item.richText)
      console.log("护工端banner", swiperList.value)
    } else {
      throw new Error('返回的banner数据格式不正确')
    }
  } catch (err) {
    console.error('获取banner数据出错:', err)
    // swiperList.value = [{
    //   url: '/static/images/default-banner.jpg',
    //   richText: ''
    // }]
    uni.showToast({
      title: '获取banner数据失败，请稍后重试',
      icon: 'none'
    })
  }
}

const handleClick = () => {
  uni.navigateTo({ url: '/pages/login/index' })
}

const noticeContent = ref("");

// 获取通知内容
const fetchNotice = async () => {
  try {
    const res = await getNoticeList();
    if (res.code === 200 && Array.isArray(res.data)) {
      const type2Notice = res.data.find(item => item.noticeType === 'type2');
      if (type2Notice) {
        noticeContent.value = type2Notice.notice;
      }
    }
  } catch (err) {
    console.error('获取通知失败:', err);
  }
};

const fetchActivityArticles = async () => {
  try {
    const res = await getActivityArticle()
    if (res.code === 200 && Array.isArray(res.data)) {
      // 过滤 type 为 article2 的数据
      const filteredData = res.data.filter(item => item.type === 'article2')
      // 转换为 messageList 需要的格式
      messageList.value = filteredData.map(item => ({
        title: item.name,
        cover: item.image,
        date: item.createTime.split('T')[0], // 只取日期部分
        content: item.content // 添加富文本内容
      }))
    }
  } catch (err) {
    console.error('获取活动文章失败:', err)
  }
}

onMounted(() => {
  // 移除登录状态检测
  fetchNotice();
  fetchNurseBannerData();
  fetchActivityArticles();
})

const handleNoticeClick = () => {
  uni.navigateTo({
    url: `/pages/notice/detail?content=${encodeURIComponent(noticeContent.value)}`
  });
};

const tabList = ref([
  {
    iconPath: '../../../static/tabbar/home.png',
    selectedIconPath: '../../../static/tabbar/homeHL.png',
    text: '首页',
    pagePath: '/pages/nurse-platform/index/index'
  },
  {
    iconPath: '../../../static/tabbar/example.png',
    selectedIconPath: '../../../static/tabbar/exampleHL.png',
    text: '预约日历',
    pagePath: '/pages/nurse-platform/order/order'
  },
  {
    iconPath: '../../../static/tabbar/personal.png',
    selectedIconPath: '../../../static/tabbar/personalHL.png',
    text: '个人中心',
    pagePath: '/pages/nurse-platform/my/my'
  }
]);

const currentIndex = ref(0);

const handleTabClick = (index) => {
  if (currentIndex.value !== index) {
    currentIndex.value = index;
    uni.reLaunch({ url: tabList.value[index].pagePath });
  }
};

onShow(() => {
  currentIndex.value = 0;
});

const handleContentClick = (richText) => {
  uni.navigateTo({
    url: `/pages/nurse-platform/index/content-detail?content=${encodeURIComponent(richText)}`
  });
};

const handleBannerDetail = (index) => {
  if (richText.value[index]) {
    uni.navigateTo({
      url: `/pages/banner/detail?content=${encodeURIComponent(richText.value[index])}`
    })
  } else {
    uni.showToast({
      title: '该图片暂无详细内容',
      icon: 'none',
      duration: 2000
    })
  }
}

const handleImageError = (item) => {
  console.error('图片加载失败:', item);
  uni.showToast({
    title: '图片加载失败，请稍后重试',
    icon: 'none'
  });
};

const productOrders = ref([])

onMounted(async () => {
  const wxUserId = uni.getStorageSync('userId')
  if (!wxUserId) return
  const res = await getUserOrderList({ wxUserId })
  if (res.code === 200) {
    productOrders.value = res.data || []
  }
})
const handleScan = () => {
  uni.scanCode({
    scanType: ['qrCode'],
    success: async (res) => {
      const orderNo = res.result // 假设二维码内容就是 outTradeNo
      const order = productOrders.value.find(o => o.outTradeNo === orderNo)
      if (!order) {
        uni.showToast({ title: '未找到该订单', icon: 'none' })
        return
      }
      if (order.status !== 'PAID') {
        uni.showToast({ title: '订单未支付或已核销', icon: 'none' })
        return
      }
      // 更新订单状态为已完成
      const updateRes = await updateUserOrderStatus({ id: order.id, status: 'COMPLETED' })
      if (updateRes.code === 200) {
        uni.showToast({ title: '核销成功', icon: 'success' })
        // 刷新订单列表
        const wxUserId = uni.getStorageSync('userId')
        const res = await getUserOrderList({ wxUserId })
        if (res.code === 200) {
          productOrders.value = res.data || []
        }
      } else {
        uni.showToast({ title: '核销失败', icon: 'none' })
      }
    },
    fail: () => {
      uni.showToast({ title: '扫码失败', icon: 'none' })
    }
  })
}
</script>

<style scoped lang="scss">
.page {
  padding: 0 24rpx;
  background-color: #f5f6fa;

  &-hd {
    // padding: 19rpx 0;
    font-family: PingFang SC;
    font-size: 36rpx;
    font-variation-settings: "opsz" auto;
    font-weight: 500;
    line-height: normal;
    color: #1a1a1a;
  }

  :deep(.wd-search) {
    padding: 16rpx 0px !important;
    background-color: transparent !important;

  }

  .swipper {
    height: 324rpx;
    margin: 0 auto;
    margin-top: 16rpx;
    border-radius: 24rpx;
    overflow: hidden;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .swiper-container {
    margin-bottom: 24rpx;
    position: relative;
    border-radius: 24rpx;
    overflow: hidden;

    .title {
      position: absolute;
      top: 0rpx;
      left: 0rpx;
      color: #FFF;
      padding: 6rpx 16rpx;
      border-radius: 24rpx;
      background: rgba(#000, 0.6);
    }

    :deep() {
      .custom-shadow {
        position: absolute;
        bottom: 46rpx;
        left: 46rpx;
        color: #89281f;
        background-color: #f2d39c;
        box-shadow: 0 3px 1px -2px rgb(0 0 0 / 20%), 0 2px 2px 0 rgb(0 0 0 / 14%), 0 1px 5px 0 rgb(0 0 0 / 12%);
      }
    }
  }

  .notice {
    display: flex;
    align-items: center;
    height: 80rpx;
    padding: 0 33.67rpx;
    margin: 24rpx 0 32rpx;
    background-color: #fff;
    border-radius: 16rpx;

    img,
    image {
      width: 26rpx;
      height: 26rpx;
    }

    .label {
      margin-left: 16rpx;
      font-family: PingFang SC;
      font-size: 26rpx;
      /* 文本/正文 */
      color: #1a1a1a;
    }

    .split {
      width: 2rpx;
      height: 24rpx;
      margin: 0 24rpx;
      background-color: #ececec;
    }

    .value {
      flex: 1;
      overflow: hidden;
      font-family: PingFang SC;
      font-size: 26rpx;
      color: #8c8c8c;
      text-overflow: ellipsis;
      letter-spacing: 0em;
      white-space: nowrap;
    }
  }

  :deep(.search-wrapper) {
    height: 72rpx;
    padding: 0;
    margin-bottom: 24rpx;
    border-radius: 16rpx;

    .wd-search__input {
      background-color: #fff;

      input::placeholder {
        font-size: 28rpx;
      }
    }

    .wd-icon {
      z-index: 999;
      width: 28rpx;
      height: 28rpx;
      color: #1a1a1a;
      transform: translateY(-20rpx);
    }
  }

  .content {
    padding: 16rpx 32rpx;
    background-color: #fff;
    border-radius: 16rpx;

    .list-item {
      display: flex;
      gap: 16rpx;
      align-items: center;
      padding: 16rpx 0;
      border-color: #f2f2f7;
      border-style: solid;
      border-width: 0px 0px 1rpx 0px;

      &-info {
        &>text {
          display: -webkit-box;
          /* 设置为WebKit内核的弹性盒子模型 */
          overflow: hidden;
          /* 隐藏超出范围的内容 */
          font-size: 27rpx;
          font-weight: normal;
          line-height: normal;
          color: #1a1a1a;
          text-overflow: ellipsis;
          /* 使用省略号 */
          letter-spacing: 0em;
          -webkit-box-orient: vertical;
          /* 垂直排列 */
          -webkit-line-clamp: 2;
          /* 限制显示两行 */
        }

        .items {
          display: flex;
          gap: 24rpx;
          align-items: center;
          padding: 0;
          margin-top: 20rpx;
          font-family: PingFang SC;
          font-size: 24rpx;
          font-weight: normal;
          line-height: normal;
          color: #8c8c8c;
          letter-spacing: 0em;

          test {
            list-style: none;
          }
        }
      }

      image {
        width: 182rpx;
        min-width: 182rpx;
        height: 132rpx;
        border-radius: 8rpx;
      }
    }
  }
}

.nurse-tabbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 100rpx;
  background-color: #F8F8F8;
  border-top: 1rpx solid #e5e5e5;
}

.tab-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.tab-icon {
  width: 48rpx;
  height: 48rpx;
}

.tab-text {
  font-size: 24rpx;
  color: #666;
}

.tab-item.active .tab-text {
  color: #018d71;
}

.scan-fab {
  position: fixed;
  right: 40rpx;
  bottom: calc(140rpx + env(safe-area-inset-bottom));
  z-index: 9999;
  background: #ffcc00;
  border-radius: 50%;
  width: 120rpx;
  height: 120rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 16rpx rgba(255, 204, 0, 0.18);

  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    border-radius: 50%;
    background: rgba(0, 0, 0, 0.1);
    opacity: 0;
    transition: opacity 0.3s;
  }

  &:active::after {
    opacity: 1;
  }

  .scan-icon {
    width: 56rpx;
    height: 56rpx;
    margin-bottom: 8rpx;
  }

  text {
    font-size: 24rpx;
    color: #333;
  }
}
</style>
